package com.resou.reader.bookstore.category;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.resou.reader.R;
import com.resou.reader.api.entry.BookCategoryBean;
import com.resou.reader.api.entry.BookCategoryData;
import com.resou.reader.api.entry.SortSecBean;
import com.resou.reader.api.entry.SortSubBean;
import com.resou.reader.base.ResouBaseActivity;
import com.resou.reader.bookdetail.BookDetailActivity;
import com.resou.reader.bookstore.category.adapter.SubCategoryAdapter;
import com.resou.reader.bookstore.category.view.ISubCategoryContract;
import com.resou.reader.commom.Constant;
import com.resou.reader.utils.UIHelper;
import com.resou.reader.view.AutoRadioGroup;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 分类
 */
public class SubCategoryActivity extends ResouBaseActivity<SubCategoryPresenter> implements ISubCategoryContract.ISubCategoryView, OnRefreshLoadMoreListener {
    private static final String TAG = "SubCategoryActivity";

    public static void startActivity(Context context, SortSubBean sortSubBean) {
        Intent intent = new Intent(context, SubCategoryActivity.class);
        intent.putExtra(Constant.EXTRA_SUB_CATEGROY, sortSubBean);
        context.startActivity(intent);
    }

    @BindView(R.id.ivBack)
    ImageView ivBack;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tvHeader)
    TextView tvHeader;
    @BindView(R.id.mSmartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    private SortSubBean sortSubBean;
    List<SortSecBean> sortSecBeans;
    SubCategoryAdapter subCategoryAdapter;
    int page = 0;
    String categoryId;
    String secId = "";
    String totalWord = "";
    String readingNum = "";
    String serialStatus = "";
    int height = 10;
    View viewHeader;
    /**
     * 头部筛选后的 标签名（三个）依次排列
     */
    String label = "";
    String label2 = "";
    String label3 = "";

    @Override
    public int getLayoutId() {
        return R.layout.activity_sub_category;
    }

    @Override
    public void retryRefreshData() {
        mPresenter.quearGateGoryData(categoryId, secId, totalWord, readingNum, serialStatus, page);
    }

    @Override
    protected void initStatusBar() {
    }

    @Override
    protected void initPresenter() {
        sortSubBean = getIntent().getParcelableExtra(Constant.EXTRA_SUB_CATEGROY);
        mPresenter = new SubCategoryPresenter(this, sortSubBean);
    }

    @Override
    protected void initView() {
        if (sortSubBean == null) {
            return;
        }
        categoryId = String.valueOf(sortSubBean.getCategoryId());
        sortSecBeans = sortSubBean.getSecSort();
        SortSecBean one = new SortSecBean();
        one.setSecCategoryId(0);
        one.setSecCategoryName("全部");
        sortSecBeans.add(0, one);
        tvTitle.setText(sortSubBean.getCategoryName() + "");
        subCategoryAdapter = new SubCategoryAdapter(R.layout.item_book_list, null);
        mSmartRefreshLayout.setOnRefreshLoadMoreListener(this);
        subCategoryAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        mSmartRefreshLayout.setEnableRefresh(false);
        mSmartRefreshLayout.setEnableLoadMore(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(subCategoryAdapter);
//        mSmartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        subCategoryAdapter.addHeaderView(getHeaderView());
        subCategoryAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                BookCategoryBean bookCategoryBean = (BookCategoryBean) adapter.getData().get(position);
                BookDetailActivity.startDetailActivity(SubCategoryActivity.this, bookCategoryBean.getId());
            }
        });
        mSmartRefreshLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

            }
        });
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (getScollYDistance(recyclerView) >= height) {
                    isHeader(true);
                } else {
                    isHeader(false);
                }
            }
        });
        tvHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isHeader(false);
                mRecyclerView.scrollToPosition(0);
                mRecyclerView.smoothScrollToPosition(0);
            }
        });
    }

    @Override
    public void initData() {
        mPresenter.quearGateGoryData(categoryId, secId, totalWord, readingNum, serialStatus, page);
    }

    @Override
    public void showContent() {
        dissLoading();
    }

    @Override
    public void showProgress() {
        showLoading();
    }

    @Override
    public void showError(Throwable throwable) {
        Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
        dissLoading();
        if (page == 0) {
            showNetErrorView(R.id.llContent);
        }
    }

    @Override
    public void showEmpty() {
        Toast.makeText(this, "暂无更多数据", Toast.LENGTH_SHORT).show();
    }

    @OnClick(R.id.ivBack)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        mPresenter.quearGateGoryData(categoryId, secId, totalWord, readingNum, serialStatus, page);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    @Override
    public void showCateGoryData(List<BookCategoryBean> list) {
        if (page == 0) {
            subCategoryAdapter.setNewData(list);
        } else {
            subCategoryAdapter.addData(list);
        }
    }

    @Override
    public SmartRefreshLayout getSmartRefreshLayout() {
        return mSmartRefreshLayout;
    }

    /**
     * 显示头部信息
     *
     * @param isshow
     */
    private void isHeader(boolean isshow) {
        if (isshow) {
            if (label.equals("") && label2.equals("") && label3.equals("")) {
                tvHeader.setText("已筛选： 全部");
            } else {
                tvHeader.setText("已筛选：" + label + " " + label2 + " " + label3);
            }
            tvHeader.setVisibility(View.VISIBLE);
        } else {
            tvHeader.setVisibility(View.GONE);
        }
    }

    /**
     * 動態设置头部选择器
     *
     * @return
     */
    @SuppressLint("ResourceType")
    private View getHeaderView() {
        if (viewHeader != null) {
            return viewHeader;
        }
        viewHeader = LayoutInflater.from(getApplication()).inflate(R.layout.subcategoryheader, null);
        AutoRadioGroup mAutoRadioGroup = viewHeader.findViewById(R.id.mAutoRadioGroup);
        AutoRadioGroup mRadioFontNum2 = viewHeader.findViewById(R.id.mAutoRadioGroup2);
        AutoRadioGroup mRadioStatus = viewHeader.findViewById(R.id.mAutoRadioGroup3);
        LinearLayout llSubcategoryheader = viewHeader.findViewById(R.id.llSubcategoryheader);
        mAutoRadioGroup.setOrientation(LinearLayout.HORIZONTAL);
        mRadioFontNum2.setOrientation(LinearLayout.HORIZONTAL);
        mRadioStatus.setOrientation(LinearLayout.HORIZONTAL);
        setTypeData(mAutoRadioGroup);
        setFontData(mRadioFontNum2);
        setRemindData(mRadioStatus);

        /**
         *获取 头部高度
         */
        llSubcategoryheader.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                llSubcategoryheader.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                height = llSubcategoryheader.getMeasuredHeight();
            }
        });
        return viewHeader;
    }


    /**
     * 监听recyclerView滑动高度
     *
     * @param recyclerView
     * @return
     */
    public int getScollYDistance(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }


    /**
     * 设置二级菜单项数据
     *
     * @param mAutoRadioGroup
     */
    private void setTypeData(AutoRadioGroup mAutoRadioGroup) {
        for (int i = 0; i < sortSecBeans.size(); i++) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setText(sortSecBeans.get(i).getSecCategoryName());
            radioButton.setButtonDrawable(null);
            radioButton.setTextColor(getResources().getColorStateList(R.drawable.font_check));
            radioButton.setGravity(Gravity.CENTER);
            if (i == 0) {
                radioButton.setTag("");
            } else {
                radioButton.setTag(sortSecBeans.get(i).getSecCategoryId() + "");
            }
            radioButton.setBackgroundResource(R.drawable.shap_check);
            radioButton.setTextSize(12);
            radioButton.setHeight(UIHelper.dip2px(getApplication(), 25));
            radioButton.setPadding(UIHelper.dip2px(getApplication(), 10), 3, UIHelper.dip2px(getApplication(), 10), 3);
            //设置RadioButton间距margin
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, UIHelper.dip2px(getApplication(), 3), 5, UIHelper.dip2px(getApplication(), 3));
            mAutoRadioGroup.addView(radioButton, params);
            if (i == 0) {
                mAutoRadioGroup.check(radioButton.getId());
                radioButton.setChecked(true);
            }
        }
        mAutoRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                radioButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (radioButton.getTag().equals("全部")) {
                            secId = "";
                        } else {
                            label = radioButton.getText().toString();
                            secId = (String) radioButton.getTag();
                        }
                        page = 0;
                        mPresenter.quearGateGoryData(categoryId, secId, totalWord, readingNum, serialStatus, page);
                    }
                });
            }
        });
    }

    /**
     * 设置三级级菜单项数据
     *
     * @param mAutoRadioGroup2
     */
    private void setFontData(AutoRadioGroup mAutoRadioGroup2) {
        List<String> list = new ArrayList<>();
        list.add("全部");
        list.add("50万字以下");
        list.add("50-100万字");
        list.add("100万字以上");
        for (int i = 0; i < list.size(); i++) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setText(list.get(i));
            radioButton.setButtonDrawable(null);
            radioButton.setTextColor(getResources().getColorStateList(R.drawable.font_check));
            radioButton.setGravity(Gravity.CENTER);
            if (i == 0) {
                radioButton.setTag("");
            } else if (i == 1) {
                radioButton.setTag("1");
            } else if (i == 2) {
                radioButton.setTag("2");
            } else if (i == 3) {
                radioButton.setTag("3");
            }
            radioButton.setBackgroundResource(R.drawable.shap_check);
            radioButton.setTextSize(12);
            radioButton.setHeight(UIHelper.dip2px(getApplication(), 25));
            radioButton.setPadding(UIHelper.dip2px(getApplication(), 10), 3, UIHelper.dip2px(getApplication(), 10), 3);
            //设置RadioButton间距margin
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, UIHelper.dip2px(getApplication(), 3), 5, UIHelper.dip2px(getApplication(), 3));
            mAutoRadioGroup2.addView(radioButton, params);
            if (i == 0) {
                mAutoRadioGroup2.check(radioButton.getId());
                radioButton.setChecked(true);
            }
        }
        mAutoRadioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                radioButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (radioButton.getText().equals("全部")) {
                            label2 = "";
                            totalWord = "";
                        } else {
                            label2 = (String) radioButton.getText();
                            totalWord = (String) radioButton.getTag();
                        }
                        page = 0;
                        mPresenter.quearGateGoryData(categoryId, secId, totalWord, readingNum, serialStatus, page);
                    }
                });
            }
        });
    }


    /**
     * 设置四级级菜单项数据
     *
     * @param mAutoRadioGroup2
     */
    private void setRemindData(AutoRadioGroup mAutoRadioGroup2) {
        List<String> list = new ArrayList<>();
        list.add("全部");
        list.add("最热");
        list.add("完结");
        list.add("连载");
        list.add("包月");
        for (int i = 0; i < list.size(); i++) {
            RadioButton radioButton = new RadioButton(this);
            radioButton.setText(list.get(i));
            radioButton.setButtonDrawable(null);
            radioButton.setTextColor(getResources().getColorStateList(R.drawable.font_check));
            radioButton.setGravity(Gravity.CENTER);
            if (i == 0) {
                radioButton.setTag("");
            } else if (i == 1) {
                radioButton.setTag("最热");
            } else if (i == 2) {
                radioButton.setTag("3");
            } else if (i == 3) {
                radioButton.setTag("1");
            } else if (i == 4) {
                radioButton.setTag("");
            }
            radioButton.setBackgroundResource(R.drawable.shap_check);
            radioButton.setTextSize(12);
            radioButton.setHeight(UIHelper.dip2px(getApplication(), 25));
            radioButton.setPadding(UIHelper.dip2px(getApplication(), 10), 3, UIHelper.dip2px(getApplication(), 10), 3);
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.setMargins(5, UIHelper.dip2px(getApplication(), 3), 5, UIHelper.dip2px(getApplication(), 3));
            mAutoRadioGroup2.addView(radioButton, params);
            if (i == 0) {
                mAutoRadioGroup2.check(radioButton.getId());
                radioButton.setChecked(true);
            }
        }
        mAutoRadioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                RadioButton radioButton = findViewById(checkedId);
                radioButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        label3 = (String) radioButton.getText();
                        if (radioButton.getText().equals("全部")) {
                            label3 = "";
                            readingNum = "";
                            serialStatus = "";
                        } else if (radioButton.getText().equals("最热")) {
                            readingNum = (String) radioButton.getTag();
                        } else if (radioButton.getText().equals("完结")) {
                            readingNum = "";
                            serialStatus = (String) radioButton.getTag();
                        } else if (radioButton.getText().equals("连载")) {
                            readingNum = "";
                            serialStatus = (String) radioButton.getTag();
                        } else {
                            readingNum = "";
                            serialStatus = "";
                        }
                        page = 0;
                        mPresenter.quearGateGoryData(categoryId, secId, totalWord, readingNum, serialStatus, page);
                    }
                });
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        ClassicsFooter.REFRESH_FOOTER_NOTHING = "已显示全部到其他分类看看吧";

    }

    @Override
    protected void onStop() {
        super.onStop();
        ClassicsFooter.REFRESH_FOOTER_NOTHING = "已经全部加载完毕";
    }
}
